<?php

/**
 * This is the model class for table "product_photos".
 *
 * The followings are the available columns in table 'product_photos':
 * @property integer $id
 * @property string $photo_path
 * @property string $description_en
 * @property string $description_th
 * @property integer $display_order
 * @property integer $enable
 * @property string $created_date
 * @property string $updated_date
 * @property string $product_id
 *
 * The followings are the available model relations:
 * @property Products $product
 * @property Products[] $products
 */
class ProductPhotos extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return ProductPhotos the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'product_photos';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('photo_path, display_order, product_id', 'required'),
			array('display_order, enable', 'numerical', 'integerOnly'=>true),
			array('photo_path', 'length', 'max'=>255),
			array('product_id', 'length', 'max'=>10),
			array('description_en, description_th, created_date, updated_date', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, photo_path, description_en, description_th, display_order, enable, created_date, updated_date, product_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'product' => array(self::BELONGS_TO, 'Products', 'product_id'),
			'products' => array(self::HAS_MANY, 'Products', 'default_photos_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'photo_path' => 'Photo Path',
			'description_en' => 'Description En',
			'description_th' => 'Description Th',
			'display_order' => 'Display Order',
			'enable' => 'Enable',
			'created_date' => 'Created Date',
			'updated_date' => 'Updated Date',
			'product_id' => 'Product',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('photo_path',$this->photo_path,true);
		$criteria->compare('description_en',$this->description_en,true);
		$criteria->compare('description_th',$this->description_th,true);
		$criteria->compare('display_order',$this->display_order);
		$criteria->compare('enable',$this->enable);
		$criteria->compare('created_date',$this->created_date,true);
		$criteria->compare('updated_date',$this->updated_date,true);
		$criteria->compare('product_id',$this->product_id,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
  public function savePhoto($productId)
  {
      //$model=new AccommodationPhoto;
      $this->product_id = $productId;
      $this->enable = 1;
      $this->display_order = $this->_nextDisplayOrder();

      $path = '/uploads/images/product_photos/'. $this->product_id  .'/';

      if(!is_dir(Yii::getPathOfAlias('webroot').$path)) {
         mkdir(Yii::getPathOfAlias('webroot').$path);
         chmod(Yii::getPathOfAlias('webroot').$path, 0755);
      }

      //save image
      $image = CUploadedFile::getInstanceByName('imagePhoto');
      if ($image && $image->saveAs(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name)) {
        //edit file
        $file = Yii::app()->image->load(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name);

        $photoName = $this->_randomName();

        $file->resize(776, 437, Image::WIDTH);
        $file->save(Yii::getPathOfAlias('webroot').$path.$photoName.'.jpg');
        $file->resize(110, 110);
        $file->save(Yii::getPathOfAlias('webroot').$path. $photoName.'_s.jpg');
        $file->resize(105, 100, Image::WIDTH)->crop(105, 100);
        $file->save(Yii::getPathOfAlias('webroot').$path. $photoName.'_t.jpg');
        unlink(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name);
        $ret = $path.$photoName.'.jpg';
        $this->photo_path = $ret;
        $this->save();

        if ($this->display_order==1 && $this->product->default_photo_id==null) {
          $this->product->default_photo_id = $this->id;
          $this->product->save();
        }

        return 1;
      }else {
        return 0;
      }
      
  }

  public function getMaxDisplayOrder()
  {
    $criteria = new CDbCriteria;
    $criteria->select='MAX(display_order) as display_order';
    $criteria->condition='product_id =  :productId';
    $criteria->params=array(':productId'=> $this->product_id);
    $model = $this->find($criteria);
    return $model->display_order;
  }

  public function _nextDisplayOrder()
  {
    $max = $this->getMaxDisplayOrder();
    $ret = isset($max) ? ($max+1) : 1;
    return $ret;
  }

  public function _randomName($num_require=8) {
    return substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789'),0,12);
  }

  public function getThumbnailPath()
  {
    if (($lastDotPosition = strrpos($this->photo_path, '.')) == true) {
      return substr_replace($this->photo_path, '_t', $lastDotPosition, 0);
    }
  }

  public function getDescription()
  {
    $ret = $this->description_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->description_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->description_en;
      }
    }

    return $ret;
  }		
}